<template>
  <VDialog
    @close="handleClose"
    @save="save"
    :loading="loading"
    title="设置换汇渠道"
    :disabled="true"
  >
    <template #content>
      <div class="mb-[8px]">
        <div class="flex">
          <VSelects
            v-model="formValues.bank"
            :dataSourse="optionDataAll?.channel || []"
            labelField="channelName"
            valueField="id"
            placeholder="渠道银行"
            multiple
            collapse-tags
            class="w-[300px]"
            collapse-tags-tooltip
          />
          <el-button class="ml-auto" type="primary" @click="handleAdd"
            >添加</el-button
          >
        </div>
      </div>
      <vxe-grid v-bind="gridOptions" ref="tableRef"></vxe-grid>
    </template>
  </VDialog>
</template>
<script setup lang="jsx">
import { ElMessage } from "element-plus";
import { setExchangeRate, deleteExchangeRate } from "../../../api.js";
const emit = defineEmits(["update:modelValue", "close", "refresh"]);
const props = defineProps({
  data: { type: Array, default: () => [] },
  optionData: { type: String, default: "" },
});
const { data, optionData } = toRefs(props);
const formValues = ref({
  bank: null,
});
const gridOptions = reactive({
  height: "400px",
  columnConfig: {
    resizable: true,
  },
  loading: false,
  size: "mini",
  columns: [
    { type: "seq", width: 80, title: "序号" },
    {
      title: "换汇渠道",
      field: "channelName",
    },
    {
      title: "操作",
      width: 100,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <el-button
                size="small"
                link
                type="danger"
                onClick={() => handleDelete(row)}
              >
                删除
              </el-button>
            </div>
          );
        },
      },
    },
  ],
  data: [],
});
watch(
  () => data.value,
  (val) => {
    if (val.length < 1) return;
    gridOptions.data = val
  },
  { immediate: true }
);
const optionDataAll = computed(() => {
  return optionData.value
});
watchEffect(() => {
  if (
    gridOptions?.data?.length < 1 ||
    optionDataAll?.value?.channel?.length < 1
  )
    return;
  formValues.value.bank = gridOptions.data.map((item) => {
    return item.channelId;
  });
});
const handleDelete = async (row) => {
  //从gridOptions.data中删除一条数据
  const { code, message } = await deleteExchangeRate({ ids: [row.channelId] });
  if (code != 200) {
    ElMessage.error(message);
    return;
  }
  ElMessage.success("删除成功");
  let data = gridOptions.data.filter((item) => {
    return item.channelId !== row.channelId;
  });
  gridOptions.data = data;
};
const handleAdd = async () => {
  if (!formValues.value.bank || formValues.value.bank.length < 1) {
    ElMessage.warning("请选择渠道银行");
    return;
  }
  let channels = optionDataAll.value.channel
    .filter((item) => {
      return formValues.value.bank.includes(item.id);
    })
    .map((item) => {
      return {
        channelType: item.channelType.value,
        channelId: item.id,
      };
    });
  try {
    const { code, message } = await setExchangeRate({ channels });
    if (code != 200) {
      ElMessage.error(message);
    }
    ElMessage.success("添加成功");
    let tabelData = optionDataAll.value.channel.filter((item) => {
      return formValues.value.bank.includes(item.id);
    });
    let data = [...gridOptions.data, ...tabelData];
    //对data根据channelId去重
    let uniqueData = data.reduce((prev, cur) => {
      let hasCur = prev.find((item) => {
        return item.channelId === cur.channelId;
      });
      if (!hasCur) {
        prev.push(cur);
      }
      return prev;
    }, []);
    gridOptions.data = uniqueData;
  } catch (error) {}
};
// const save = async () => {};
const handleClose = async (refresh) => {
  emit("update:modelValue", false);
  emit("close");
  if (refresh) emit("refresh");
};
const loading = ref(false);
</script>
<style lang="scss" scoped></style>
